<?php

class Users
{
    var $pdo = null;
    var $logger = null;
    function __construct()
    {
        $this->pdo = PDOWrapper::instance();
        $this->logger = CLog::getInstance();
    }

    /**
     * @return array|bool
     * 
     * 饭店
     */
    function LoginV1($GetParams, $PostArray){

        if(!isset($GetParams['r_id'])){
            Utils::ShowError(ErrorDefine::REQUIRED_FIELD_EMPTY);
            return false;
        }
        if(!isset($GetParams['table_id'])){
            Utils::ShowError(ErrorDefine::REQUIRED_FIELD_EMPTY);
            return false;
        }

        $openid = 'oOeWQw72tMDZeTG-GpmpPze7iUx4';

        if (!isset($openid)) {
            Utils::ShowError(ErrorDefine::REQUIRED_FIELD_EMPTY);
            return false;
        }

        $user_info = $this->pdo->select('users',array('user_id','user_name','user_pic'),array('wechat_openid'=>$openid));
        
        if (empty($user_info)) {
            self::new_user($openid);
        }

        $user_id = $user_info[0]['user_id'];
        $token = $user_id.User::TOKEN_DELIM.$GetParams['r_id'].User::TOKEN_DELIM.$GetParams['table_id'].User::TOKEN_DELIM.time();
        $crypt = new MyCrypt(CRYPT_KEY);
        $token = $crypt->encrypt($token);
        
        $params = [
            'r_id' => $GetParams['r_id']
        ];
        $field = [
            'r_id','r_name','r_location','r_logo'
        ];
        $r_info = $this->pdo->select('restaurant', $field, $params);
        if (empty($r_info)) {
            Utils::ShowError(ErrorDefine::ILLEGALL_RESTAURANT);
            return false;
        }
        $this->pdo->update('users',array('token'=>$token),array('user_id'=>$user_id));

        $user_info = [
            'user_pic' => $user_info[0]['user_pic'],
            'user_name' => $user_info[0]['user_name'],
            'token' => $token,
        ];
        $message = [
            'r_info' => $r_info,
            'user_info' => $user_info
        ];
        Utils::ShowMessage($message);
        return true;
    }


}